console.log('[shopReport] 加载插件')
var pages = $($('td.smaller')[2])

// 当前页
var current = 1
// 是否已经设置点击动作
var isSetClicked = false
// 跳转间隔时间
var goto_time = 2000

function handler() {
    // 过滤'请求报告'按钮，并点击
    var buttons = $('.regenerateButton')
    if (buttons.length > 0) {
        console.log('[shopReport] 正在点击“请求报告”按钮')
        buttons.each(function() {
            this.click()
        })
        location.href = location.href
        return
    }

    // 过滤'报告生成中'，等待生成结束
    var labels = $('.progressText')
    if (labels.length > 0) {
        console.log('[shopReport] 等待报告生成')
        location.href = location.href
        return
    }

    // 过滤'下载模板文件'按钮，并点击
    buttons = $.merge($('.buttonImage[name="下载模板文件"]'), $('.buttonImage[name="Download Flat File"]'))
    var num = parseInt($($('.currentpagination')[0]).text()) || 1
    if (buttons.length > 0 && num == current && !isSetClicked) {
        console.log('[shopReport] 开始下载模板文件，第' + current + '页，共' + buttons.length + '个')
        updateFileNum(buttons.length)
        buttons.each(function() {
            // console.log('[shopReport] 下载' + this.href)
            // setTimeout(this.click(), 0)
            // 使用window.open能达到并发下载，setTimeout无效，ajax只能返回txt类型需要额外处理
            window.open(this.href)
        })

        // 跳转
        // 判断是否最后一页：最后一项的text是否为NaN
        var text = pages.find(':last').text()
        var pageNum = $(pages[0]).children().length
        if (pageNum == 1 || (pageNum > 1 && parseFloat(text).toString() != "NaN")) {
            getFileNum()
            console.log('[shopReport] 完成下载')
            stopWork()
        } else {
            setTimeout(function() {
                current++
                var items = pages.children()
                for (var i=0, len=items.length; i<len; i++) {
                    if ($(items[i]).text() == current) {
                        isSetClicked = false
                        updateState()
                        items[i].click()
                        break
                    }
                }                
                console.log('[shopReport] 跳转到第' + current + '页')
            }, goto_time)
            isSetClicked = true
            updateState()
        }
    } else if (buttons.length == 0) {
        console.log('[shopReport] 第' + current + '页中未发现“下载模板文件”按钮，停止下载')
        stopWork()
    }
    
}

function stopWork() {
    console.log('[shopReport] 发送停止计时器指令')
    chrome.runtime.sendMessage({
        cmd: 'stopWork'
    });
}

function updateState() {
    chrome.runtime.sendMessage({
        cmd: 'update',
        current: current,
        isSetClicked: isSetClicked
    });
}

function updateFileNum(num) {
    chrome.runtime.sendMessage({
        cmd: 'updateFileNum',
        fileNum: num
    });
}

function getFileNum() {
    chrome.runtime.sendMessage({
        cmd: 'getFileNum'
    });
}

// 接收来自后台的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
    switch (request.cmd) {
        case 'startWork':
            if (pages != null && pages.length > 0) {
                var text = pages.find(':first').text()
                var pageNum = $(pages[0]).children().length
                if (pageNum > 1 && parseFloat(text).toString() == "NaN") {
                    alert('请先返回第一页后再点击“开始下载”')
                    return
                }

                current = request.current
                isSetClicked = request.isSetClicked
                sendResponse({
                    type: 'startWork_callback'
                })
                console.log('[shopReport] 开始执行下载')
            } else {
                console.log('[shopReport] 无法定位到分页，停止下载')
                stopWork()
            }
            break
        case 'download':
            console.log('[shopReport] 接收指令：' + JSON.stringify(request))
            current = request.current
            isSetClicked = request.isSetClicked
            handler()
            break
        case 'stopWork':
            console.log('[shopReport] 停止下载')
            break
        case 'getFileNum_callback':
            var msg = '完成下载，共' + request.fileNum + '个文件'
            console.log(msg)
            alert(msg)
            break
    }
});
